package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.CommunityDao;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Community;
import com.atguigu.service.CommunityService;
import com.atguigu.util.CastUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CommunityService.class)
@Transactional
public class CommunityServiceImpl extends BaseServiceImpl<Community> implements CommunityService {
    @Autowired
    private CommunityDao communityDao;
    @Autowired
    private DictDao dictDao;
    @Override
    protected BaseDao<Community> getEntityDao() {
        return communityDao;
    }

    /**
     * 方案1：多表连接查询，使用resultMap而不是resultType。优点是一次查询搞定，效率高
     * 方案2：先查询小区信息（areaId，plate_ID）,针对每个小区，再分别进行两次查询，获取areaName plateName
     *       优点：简单  缺点：多次查询 效率低
     * @param filters
     * @return
     */
    @Override
    public PageInfo<Community> findPage(Map<String, Object> filters) {
        //启动分页插件(会自动的获取符合条件的总的记录数，自动给分页语句条件limit子句)
        int pageNum = CastUtil.castInt(filters.get("pageNum"));
        int pageSize = CastUtil.castInt(filters.get("pageSize"));
        PageHelper.startPage(pageNum,pageSize);
        //调用业务层查询指定页的数据（SQL语句不需要写limit，插件自动添加）
        Page<Community> page = this.communityDao.findPage(filters); //查询条件
        //目前的结果中只有areaId和plateId，没有areaName和plateName
        List<Community> result = page.getResult();
        for(Community community:result){
            String areaName = this.dictDao.getNameById(community.getAreaId());
            community.setAreaName(areaName);
            String plateName = this.dictDao.getNameById(community.getPlateId());
            community.setPlateName(plateName);
        }
        //返回数据
        return new PageInfo<Community>(page,8);
    }

    @Override
    public List<Community> findAll() {
        return this.communityDao.findAll();
    }

    @Override
    public Community getById(Serializable id) {
        //小区信息，有areaId没有areaName，有plateId没有plateName
        Community community = this.communityDao.getById(id);
        //根据areaId---->areaName
        String areaName = this.dictDao.getNameById(community.getAreaId());
        community.setAreaName(areaName);
        //根据plateId----->plateName
        String plateName = this.dictDao.getNameById(community.getPlateId());
        community.setPlateName(plateName);
        return community;
    }
}
